#include "application.h"

PFNGLGENBUFFERSPROC glGenBuffers;
PFNGLBINDBUFFERPROC glBindBuffer;
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
PFNGLBUFFERDATAPROC glBufferData;
PFNGLBLENDCOLORPROC glBlendColor;

Application::Application(int width, int height)
{
    glfwInit();

    glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 2);
    glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
    glfwOpenWindow(width, height, 8, 8, 8, 8, 24, 8, GLFW_WINDOW);

    initGlExtensions();

    _gsm = new GameStateManager();

}

Application::~Application()
{
    delete _gsm; _gsm = NULL;

    glfwCloseWindow();
    glfwTerminate();
}

void Application::run()
{
    float frametime = 0.03f, lastFpsTime = glfwGetTime();

    while (_gsm->isRunning()) {

        float startTime = glfwGetTime();

        _input.update();

        _gsm->update(frametime, _input);
        _gsm->draw();

        glfwSwapBuffers();
        glfwSleep(0.001);

        frametime = glfwGetTime() - startTime;

        // Show Fps
        if (glfwGetTime() - lastFpsTime > 1.0f) {
            char buf[16];
            sprintf(buf, "FPS: %.0f", 1 / frametime);
            glfwSetWindowTitle(buf);
            lastFpsTime = glfwGetTime();
        }
    }

}

void Application::initGlExtensions()
{
    glGenBuffers = (PFNGLGENBUFFERSPROC)glfwGetProcAddress("glGenBuffers");
    glBindBuffer = (PFNGLBINDBUFFERPROC)glfwGetProcAddress("glBindBuffer");
    glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)glfwGetProcAddress
        ("glDeleteBuffers");
    glBufferData = (PFNGLBUFFERDATAPROC)glfwGetProcAddress("glBufferData");
    glBlendColor = (PFNGLBLENDCOLORPROC)glfwGetProcAddress("glBlendColor");
}
